//
//  WKComposeViewController.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/17.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit
import SVProgressHUD

class WKComposeViewController: UIViewController {

    ///图片选择控制器
    private lazy var picturePickerController = PicturePickerController()
    
    /// 表情键盘视图
    private lazy var emoticonView: EmoticonView = EmoticonView { [weak self] (emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
    }
    
    //MARK: - 监听方法
    @objc private func close() {
    
        //关闭键盘
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
    // 发布微博
    @objc private func sendStatus() {
    
        //1.获取文本内容
        let text = textView.emoticonText
        
        //发布微博
        let image = picturePickerController.pictures.last
        
        NetworkTools.sharedTools.sendStatus(text, image: image) { (result, error) -> () in
            
            if error != nil {
            
                print("出错了")
                SVProgressHUD.showInfoWithStatus("您的网速不给力")
                return
                
            }
            
            print(result)
            
            //关闭控制器
            self.close()
            
        }
        
        
    
    }
    
    //选择图片
    @objc private func selectPicture() {
    
        //退出键盘
        textView.resignFirstResponder()
        
        //判断如果已经更新了约束,就不会再执行后面的代码
        if picturePickerController.view.frame.height > 0 {
        
            return
        }
    
        //修改图片控制器的约束
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        // 重新修改文本视图的约束
        textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePickerController.view.snp_top)
        }
        
        //动画更新约束
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
            
        }
        
    }
    
    //选择表情
    @objc private func selectEmoticon() {
    
        //1.退出键盘
        textView.resignFirstResponder()
        
        //2.设置键盘
        textView.inputView = textView.inputView == nil ? emoticonView : nil
        
        //3. 重新激活键盘
        textView.becomeFirstResponder()
    
    }
    
    //处理键盘变化
    @objc private func keyboardChanged(n: NSNotification) {
    
        print(n)
        
        let rect = (n.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        //获取动画时长
        let duration =  (n.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        
        //动画曲线
        let curve = (n.userInfo![UIKeyboardAnimationCurveUserInfoKey]as! NSNumber).integerValue
    
        let offset = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        //更新toobal的约束
        toolbar.snp_updateConstraints { (make) -> Void in
            
            //更新底部约束
            make.bottom.equalTo(view.snp_bottom).offset(offset)
            
        }
        
        //设置动画
        UIView.animateWithDuration(duration) { () -> Void in
            
            //设置动画效果
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            //更新约束
            self.view.layoutIfNeeded()
            
        }
        
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 添加键盘的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //注销通知
    deinit {
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }

    //MARK: - 视图声明周期
    override func loadView() {
        
        view = UIView()
        
        //更新视图
        setUpUI()
    }

    //激活键盘
    override func viewDidAppear(animated: Bool) {
        
        super.viewDidAppear(animated)
        
        //判断当出现图片控制器就不弹出键盘
        if picturePickerController.view.bounds.height == 0 {
        
            textView.becomeFirstResponder()
        }
        
        
    }
    
    
    ///懒加载控件
    //工具条
    private lazy var toolbar = UIToolbar()

    //文本视图
    private lazy var textView:UITextView = {
    
        let tv = UITextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        
        //始终允许垂直滚动
        tv.alwaysBounceVertical = true
        //拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        tv.delegate = self
        
        return tv
    }()
    
    //占位标签
    private lazy var placeHolderLabel:UILabel = UILabel(title: "分享新鲜事...", color:UIColor.lightGrayColor() , fontSize: 18)

}

// MARK: - UITextViewDelegate
extension WKComposeViewController: UITextViewDelegate {

    func textViewDidChange(textView: UITextView) {
        
        //判断发送按钮的禁用状态
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        placeHolderLabel.hidden = textView.hasText()
        
    }

}


/// MARK: - 设置界面
private extension WKComposeViewController {

    func setUpUI(){
    
            //取消自动调整滚动视图间距
        automaticallyAdjustsScrollViewInsets = false
        
        
            //设置背景颜色
        view.backgroundColor = UIColor.whiteColor()
    
            //设置控件
        prepareNavigationBar()
        prepareToolbar()
        prepareTextView()
        preparePicturePicker()
    
    }
    
    /// 准备图片选择控制器
    private func preparePicturePicker() {
    
        //1.添加子控制器
        addChildViewController(picturePickerController)
        
        view.insertSubview(picturePickerController.view, belowSubview: toolbar)
        
        //自动布局
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(0)
        }
    
    }
    
    //设置文本
    private func prepareTextView() {
        
        view.addSubview(textView)
        
        //设置自动布局
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        
        //添加占位标签
        textView.addSubview(placeHolderLabel)
        
        //自动布局
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
        
    }

    
    //设置toobar
    private func prepareToolbar() {
    
        //添加控件
        view.addSubview(toolbar)
        
        //设置背景颜色
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        //自动布局
        toolbar.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
            
        }
        
        //添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture", "actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]

        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
        
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"]))
            
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        
        }
        
        //移除最后的弹簧
        items.removeLast()
        
        toolbar.items = items
        
    }
    
    
    
    
    //设置导航栏
    private func prepareNavigationBar() {
        
        //1.左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "sendStatus")
        
        
         //禁止发布微博按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        //标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 36))
        
        navigationItem.titleView = titleView
        
        //添加子控件
        let titleLabel = UILabel(title: "发微博",  fontSize: 15 )
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.account?.screen_name ?? "", color: UIColor.lightGrayColor(), fontSize: 13)
        
        //添加控件
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        
    }


}



